package aole.visq.draw;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.Externalizable;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

import javax.imageio.ImageIO;

public class SerializedBI implements Externalizable {
	private BufferedImage	image;
	private Graphics2D		g2;

	public SerializedBI() {}

	public SerializedBI( BufferedImage i ) {
		image = i;
		g2 = i.createGraphics();
		g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING,
				RenderingHints.VALUE_ANTIALIAS_ON );
		g2.setBackground( new Color( 0, 0, 0, 0 ) );
		g2.setColor( Color.black );
	}

	public SerializedBI( File f ) throws IOException {
		this( ImageIO.read( f ) );
	}

	public SerializedBI( int w, int h, int t ) {
		this( new BufferedImage( w, h, t ) );
	}

	public void setStrokeColor( Color c ) {
		g2.setColor( c );
	}

	public BufferedImage getImage() {
		return image;
	}

	public Graphics2D getGraphics() {
		return g2;
	}

	public void writeExternal( ObjectOutput out ) throws IOException {
		if( image == null ) {
			out.writeBoolean( false );
			return;
		}
		out.writeBoolean( true );
		out.writeInt( image.getWidth() );
		out.writeInt( image.getHeight() );
		out.writeInt( image.getType() );

		for( int y = 0; y < image.getHeight(); y++ )
			for( int x = 0; x < image.getWidth(); x++ )
				out.writeInt( image.getRGB( x, y ) );
	}

	public void readExternal( ObjectInput in ) throws IOException,
			ClassNotFoundException {
		int width, height, type;
		if( in.readBoolean() ) {
			width = in.readInt();
			height = in.readInt();
			type = in.readInt();
			image = new BufferedImage( width, height, type );

			for( int y = 0; y < height; y++ )
				for( int x = 0; x < width; x++ )
					image.setRGB( x, y, in.readInt() );

			g2 = image.createGraphics();
			g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING,
					RenderingHints.VALUE_ANTIALIAS_ON );
			g2.setBackground( new Color( 0, 0, 0, 0 ) );
			g2.setColor( Color.BLACK );
		} else image = null;
	}

	public void drawImage( BufferedImage img ) {
		g2.clearRect( 0, 0, img.getWidth(), img.getHeight() );
		g2.drawImage( img, 0, 0, null );
	}
}